function replyMessage($receiverId, $msgContent) {

    var alertData = "";
    var is_success = false;
    var id = "";
    $.ajax({
        url: baseUrl + "/ajax/replymessage/format/json",
        data: {
            receiverId: $receiverId,
            msgContent: $msgContent
        },
        async: false,
        dataType: "json",
        success: function(data) {

            //console.log(data.success);
            if (data.success) {
                is_success = true;
                id = data.id;
                Alert("Alert message", "Message successfully sent!");
            } else {
                Alert("Alert message", "Oops!! an error occurred while sending message!");
            }
        }

    });

    if (is_success) {
        var returnObj = {
            "id": id,
            "success": true,
            "failure": false
        };
    }
    else {
        var returnObj = {
            "success": false,
            "failure": true
        };
    }

    return returnObj;
}

function outboxUpdate(page) {
    if (!page)
        page = 1;
    $.ajax({
        url: baseUrl + "/ajax/outbox/format/json/page/" + page,
        dataType: "json",
        success: function(data) {
            if (!data.error) {
                $('#outbox-only-messages').empty().mustache('inbox-msg-tmplt', data, {
                    method: 'html'
                });
                $('.outbox-count').empty().mustache('outbox-count', data, {
                    method: 'html'
                });
            }
            else {
                Alert("Alert message", "Session time out!");
                window.location.href = baseUrl;
            }
        }
    });

}
function myreviewUpdate(user_id, page) {
    $('.reviews-list').mask("Loading..");
    $.ajax({
        url: baseUrl + "/ajax/getmyreview/format/json/user_id/" + user_id + "/page/" + page,
        dataType: "json",
        success: function(data) {
            if (!data.error) {
                $('.reviews-list').unmask();
                $('.reviews-list').empty();
                $('.reviews-list').mustache('my-review-list', data, {
                    method: 'html'
                });
            }
            else {
                Alert("Alert message", "Oops! some error occurred");
                window.location.href = baseUrl;
            }
        }
    });
}
function myratingUpdate(user_id, page) {
    $('.rates-list').mask("Loading..");
    $.ajax({
        url: baseUrl + "/ajax/getmyrate/format/json/user_id/" + user_id + "/page/" + page,
        dataType: "json",
        success: function(data) {
            if (!data.error) {
                $('.rates-list').unmask();
                $('.rates-list').empty();
                $('.rates-list').mustache('myrating-template', data, {
                    method: 'html'
                });
            }
            else {
                Alert("Alert message", "Oops! some error occurred");
                window.location.href = baseUrl;
            }
        }
    });
}

function pagingUpdate(page, user_id, context) {

    $.ajax({
        url: baseUrl + "/ajax/getpagination/format/html/page/" + page + "/user_id/" + user_id + "/context/" + context,
        success: function(data) {
            switch (context) {
                case 'review' :
                    $('#myreview-pagination').empty().html(data);
                    break;
                case 'rating' :
                    $('#myrates-pagination').empty().html(data);
                    break;
                case 'message_inbox':
                    $('#message-pagination-inbox').empty().html(data);
                    break;
                case 'message_outbox':
                    $('#message-pagination-outbox').empty().html(data);
                    break;

            }
        }
    });
}

function inboxUpdate(page) {
    if (!page)
        page = 1;
    $.ajax({
        url: baseUrl + "/ajax/inbox/format/json/page/" + page,
        dataType: "json",
        success: function(data) {
            if (!data.error) {
                $('#inbox-only-messages').empty().mustache('inbox-msg-tmplt', data, {
                    method: 'html'
                });
                $('.inbox-count').empty().mustache('inbox-count', data, {
                    method: 'html'
                });
            }
            else {
                Alert("Alert message", "Session time out!");
                window.location.href = baseUrl;
            }
        }
    });
}

function addFriend(userId, groupId, This) {

    $('.add-friends a').mask('Requesting..');
    //$('.add-friends a').html('<span class="txt">Request sent</span>');
    $.ajax({
        url: baseUrl + "/ajax/addfriend/format/json/user_id/" + userId + "/group_id/" + groupId,
        dataType: "json",
        async: false,
        success: function(data) {
            if (!data.error) {
                //var html = $('<ul class="dropdown" style="display:block">');
                //var ohtml = '';
                $(This).parent('ul').children('li').each(function(index, data) {
                    //console.log($(this).get(0),$(This).get(0))
                    if ($(this).get(0) == $(This).get(0))
                        $(this).remove();
                //html.append($(this).get(0));
                //console.log(data);
                });


                //console.log(html);
                //$('.add-friends a').html('<span class="txt">Add to another group</span><span class="arrow"></span>');
                $('.add-friends a').unmask();

                //                window.location.href = window.location.href.split("#")[0];
                Alert("Alert message", data.message, "1");


            }
            else {
                $('.add-friends a').unmask();
                Alert("Alert message", data.message);

            }
        }
    });

}

function validateForm(context, form) {

    var $form = $(form);
    //$form.children('.commentEnter').trigger("onclick");
    //console.log($form.children('.commentEnter')); return false;

    switch (context) {

        case 'reply':
            console.log($form);
            if ($form.find('.commbox').val() == 'Write a comment ...' || !$form.find('.commbox').val()) {
                Alert("Alert message", 'please enter comment!');
                return false;
            }
            if (!$form.find('.message_to').val()) {
                Alert("Alert message", 'please select receiver!');
                return false;
            }
            //$form.children('.commentEnter').trigger('click');
            //return false;
            commentEnterClick($form);
            break;
        case 'profile_comment':
            if ($form.find('.commbox').val() == 'Write a comment ...' || !$form.find('.commbox').val()) {
                Alert("Alert message", 'please enter comment!');
                return false;
            }
            if (!$form.find('#user_rate_to').val()) {
                Alert("Alert message", 'please comment on some profile!');
                return false;
            }
            return true;
            break;
        default:
            Alert("Alert message", 'Oops!! some error occurred');
            return false;

    }

    return false;
}
function commentEnterClick($form) {

    $('.im-content, #im').mask("Sending..");



    var receiverId = $.trim(parseInt($form.find('.message_to').val()));
    var msgContent = $form.find('.commbox').val();

    //check if valid receiver
    if (!receiverId) {

        Alert("Alert message", 'please select sender and then reply!');


    }


    var returnObj = replyMessage(receiverId, msgContent);

    if (returnObj.success) {
        outboxUpdate();
    }

    $form.find('.commbox').val("");
    //$form.children('.commbox').val("");
    $form.closest('.reply-box').css("display", "none");
    $form.closest('.msg-right').find(".reply").css("display", "block");
    $('.im-content, #im').unmask();
}

function deleteMessage(url, is_inbox) {

    $('.im-content').mask("Sending..");
    $.ajax({
        url: url,
        async: false,
        dataType: "json",
        success: function(data) {

            if (data.error) {
                Alert("Alert message", data.message);
            } else {
                Alert("Alert message", data.message);

            }
        }

    });
    if (is_inbox == 'true') {
        inboxUpdate();
    } else {
        outboxUpdate();
    }
    $('.im-content').unmask();
}

function updateSubcategory(catId) {
    $('#subcat-id').children('blu').empty().text('-- Select --');
    $('#subcat-id').children('dropdown').children('ul').empty().append('<li data-subcid="0">-- Select --</option');

    getSubcategories(catId);


}
function getSubcategories(catId) {

    $.ajax({
        url: baseUrl + "/ajax/getsubcategories/catId/" + catId,
        dataType: "json",
        async: false,
        success: function(data) {
            if (data.error)
            {
                Alert("Alert message", data.message);
                return;

            }
            else
            {
                var subcatArr = [];
                //console.log($(_this),$(_this).find('select'));
                //console.log($('#subcat-id').children('dropdown').children('ul'));
                for (var i in data.data) {

                    $('#subcat-id').children('.dropdown').children('ul').append('<li data-target="event_subcat_id" data-val="' + data.data[i]['subcategory_id'] + '">' + data.data[i]['subcategory_name'] + '</li>');

                }
            //return subcatArr;

            }
        }
    });



}

function addRecurringDates() {
    var html = $('#recurring_date').html();
    //console.log($('#recurring input'));
    var count = parseInt($('#recurring input').length / 3) + 1;
    //    console.log(count)
    html = html.replace(/recurring_date_/g, "recurring_date_" + count);
    html = html.replace(/recurr-/g, "recurr-" + count);
    $('#recurring').append(html);
}

function uploadEventVideo() {
    var url = $('#event_video').val(), reg = /youtube/,
    videoType = reg.test(url) ? 'youtube' : 'vimeo', youtube = /v=(.{11})/,
    vimeo = /vimeo\.com\/([0-9]{1,10})/, id = '', iframe = $('<iframe />'), flag_error = false;

    console.log(iframe);
    if (videoType == 'youtube') {
        id = url.match(youtube);
        iframe[0].src = "http://www.youtube.com/embed/" + id[0];
        iframe[0].width = "333";
        iframe[0].height = "204";
        $('.video-prv').empty().append(iframe);
    } else {
        if (videoType == 'vimeo') {
            id = url.match(vimeo);
            iframe[0].src = "http://player.vimeo.com/video/" + id[0];
            iframe[0].width = "333";
            iframe[0].height = "204";
            $('.video-prv').emtpy().append(iframe);
        } else {
            flag_error = true;
        }
    }

    if (id.length <= 0)
        flag_error = true;

    if (flag_error)
        Alert("Alert message", "Please enter a valid video url");
}

function setup_reader(file) {
    var fileDisplayArea = document.getElementById('fileDisplayArea');
    var imageType = /image.*/;

    if (file.type.match(imageType)) {
        var reader = new FileReader();

        reader.onload = function(e) {
            //fileDisplayArea.innerHTML = "";

            var img = new Image();
            img.src = reader.result;
            img.width = 82;
            img.height = 46;

            //add to li
            //var input = $('<input type="hidden" name="event_image_file[]" value="'+reader.result+'">');
            var li = $(img).after('').wrap('<a href="#">').wrap('<li>');
            //$('.upload-button').after(input.get(0));
            fileDisplayArea.appendChild(li.get(0));
        }

        reader.readAsDataURL(file);
    } else {
        fileDisplayArea.innerHTML = "File not supported!"
    }

}

function uploadEventImage() {

    var fileInput = document.getElementById('event_image');
    var fileDisplayArea = document.getElementById('fileDisplayArea');

    $(fileDisplayArea).empty();
    for (var i = 0; i < fileInput.files.length; i++)
    {

        setup_reader(fileInput.files[i]);


    }
}

//below is alert script

function Alert(Title, Content, redirect_uri) {
    //$("body").prepend('<a id="alert" href="#alert-msg">alert</a>');



    if (Title)
        $('#alert-msg').find('.title').html(Title)

    if (Content)
        $('#alert-msg').find('.content').html(Content)

    $('#alert-msg').closest('.lytebox-wrap').css("z-index", "10000");
    $('#alert').click();

    if (redirect_uri=="1")
    {
        $('.show-profile .close-button, .lytebox-overlay').live('click', function() {
            window.location.href = window.location.href.split("#")[0];
        });
    }
}

function Confirm(Title, Content, friend_id, groupId) {


    if (Title)
        $('#confirm-msg').find('.title').html(Title)

    if (Content)
        $('#confirm-msg').find('.content').html(Content);


    $('#confirmBox').click();

    $('#confirm-msg .Cancel').click(function(e) {

        $('#confirm-msg .close-button').click();

    });


    $('#confirm-msg .confirm').click(function(e) {
        //        var friend_id = parseInt($(".remove-friend").attr('rel'));

        //$('#confirm-msg .close-button').click();
        closeBox('confirm');
        //below statements are for friend list

        var url = baseUrl + "/friend/removefriend?friend_id=" + friend_id + "&group_id=" + groupId;
        window.location.href = url;
        return false;
    });

}

function ConfirmRemoveEventMember(Title, Content, url, div_id) {


    if (Title)
        $('#confirm-msg').find('.title').html(Title)

    if (Content)
        $('#confirm-msg').find('.content').html(Content);


    $('#confirmBox').click();

    $('#confirm-msg .Cancel').click(function(e) {

        $('#confirm-msg .close-button').click();

    });


    $('#confirm-msg .confirm').click(function(e) {

        //$('#confirm-msg .close-button').click();
        closeBox('confirm');
        //below statements are for friend list
        $(".please-wait").show();
        $.ajax({
            url: url,
            success: function() {
                $("#" + div_id).remove();
                location.reload();
            }
        });
        return false;
    });

}

function ConfirmAddEventMember(Title, Content, url, div_id) {


    if (Title)
        $('#confirm-msg').find('.title').html(Title)

    if (Content)
        $('#confirm-msg').find('.content').html(Content);


    $('#confirmBox').click();

    $('#confirm-msg .Cancel').click(function(e) {

        $('#confirm-msg .close-button').click();

    });


    $('#confirm-msg .confirm').click(function(e) {

        //$('#confirm-msg .close-button').click();
        closeBox('confirm');
        //below statements are for friend list
        $.ajax({
            url: url,
            success: function() {
                var cl = $('#' + div_id).clone();
                $(".please-wait").show();
                //                $("#" + div_id).remove();
                //                $('.post-content .friends .own-event.friend-wrap div.fleft ul').append(cl);
                window.location = window.location.href.split("#")[0];


            }
        });
        return false;
    });

}



function ConfirmDeleteEvent(Title, Content, url, div_id) {


    if (Title)
        $('#confirm-msg').find('.title').html(Title)

    if (Content)
        $('#confirm-msg').find('.content').html(Content);


    $('#confirmBox').click();

    $('#confirm-msg .Cancel').click(function(e) {

        $('#confirm-msg .close-button').click();

    });


    $('#confirm-msg .confirm').click(function(e) {

        //$('#confirm-msg .close-button').click();
        closeBox('confirm');
        //below statements are for friend list
        $.ajax({
            url: url,
            success: function() {
                $("#" + div_id).remove();
            }
        });
        return false;
    });

}


function ConfirmLeaveEvent(Title, Content, url, div_id) {


    if (Title)
        $('#confirm-msg').find('.title').html(Title)

    if (Content)
        $('#confirm-msg').find('.content').html(Content);


    $('#confirmBox').click();

    $('#confirm-msg .Cancel').click(function(e) {

        $('#confirm-msg .close-button').click();

    });


    $('#confirm-msg .confirm').click(function(e) {

        //$('#confirm-msg .close-button').click();
        closeBox('confirm');
        //below statements are for friend list
        $.ajax({
            url: url,
            success: function() {
                $("#" + div_id).remove();
            }
        });
        return false;
    });

}

function closeBox(context) {

    switch (context) {
        case 'confirm':
            $('#confirm-msg .close-button').click();
            break;
        case 'alert'  :
            $('#alert-msg .close-button').click();
            break;
    }
}

function lytebox() {
    $('.show-profile-test').each(function(data) {
        $(this).lytebox({
            showClose: false, 
            closeButton: $($('.show-profile-test').attr('href')).find('.close-button')
            });
    })
}

function removetempimage(_this) {
    $.ajax({
        url: baseUrl + "/ajax/removeeventimage",
        dataType: "json",
        data: {
            user_id: $(_this).data('user'), 
            file: $(_this).data('file')
            },
        success: function(data) {
            if (data.success) {
                $(_this).parent('li').remove();
            } else {
                Alert(data.message, "Alert Message");
            }
        }
    })
}

function removeImage(image, url) {
    $.ajax({
        url: baseUrl + "/ajax/removeeventimage",
        data: {
            url: url, 
            image: image
        },
        success: function(data) {

        }
    })
}

function checkLogin() {
    $.ajax({
        url: baseUrl + "/ajax/checklogin",
        dataType: "json",
        success: function(data) {
            if (data.error) {
                Alert("Please Log in before continuing!", "Alert Message");
                $('#login-button').click();
            } else {
                return true;
            }
        }
    })
}

function removeeventimage(This) {

    $('#confirm-msg').find('.content').html("Are you sure you want to remove image?");


    $('#confirmBox').click();



    $('#confirm-msg .Cancel').click(function(e) {

        $('#confirm-msg .close-button').click();

    });


    $('#confirm-msg .confirm').click(function(e) {

        //$('#confirm-msg .close-button').click();
        closeBox('confirm');
        //below statements are for friend list
        $.ajax({
            url: This.href,
            success: function() {
                $(This).parent('li').remove();
            }
        });
        return false;
    });


}


function removeCount(_this) {
    console.log(_this);

    if ($(_this).data('count')) {
        $.ajax({
            url: baseUrl + "/ajax/notificationcount",
            dataType: "json",
            data: {
                type: $(_this).data('type')
                },
            success: function(data) {
                if (data.success)
                    $(_this).find('.msg-count').remove();
            }
        });
    }
}
//Alert('Test','This is just to test the alert box');
function getDateNumber(month) {

    var dateArr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    for (var key in dateArr) {

        if (month == dateArr[key])
            return key;
    }
    return false;
}

//event chat box scroll to bottom
function scrollTOBottom(id){
    var objDiv = document.getElementById("chat-wrapper");
    objDiv.scrollTop = objDiv.scrollHeight;
}

function close_login(){
    plog.close();
}

function close_register(){
    pcaa.close();
}